import { app, BrowserWindow, shell, ipcMain, IpcMainInvokeEvent, WebContentsPrintOptions, dialog  } from 'electron';
import { release } from 'node:os';
import { join } from 'node:path';
const fs = require('fs');
const http = require('http');

import { printUtils } from '../../src/utils/printUtils';

process.env.DIST_ELECTRON = join(__dirname, '..');
process.env.DIST = join(process.env.DIST_ELECTRON, '../dist');
process.env.VITE_PUBLIC = process.env.VITE_DEV_SERVER_URL
  ? join(process.env.DIST_ELECTRON, '../public')
  : process.env.DIST;

if (release().startsWith('6.1')) app.disableHardwareAcceleration();

if (process.platform === 'win32') app.setAppUserModelId(app.getName());

if (!app.requestSingleInstanceLock()) {
  app.quit();
  process.exit(0);
}

let win: BrowserWindow | null = null;
const preload = join(__dirname, '../preload/index.js');
const url = process.env.VITE_DEV_SERVER_URL;
const indexHtml = join(process.env.DIST, 'index.html');

async function createWindow() {
  win = new BrowserWindow({
    title: 'Main window',
    icon: join(process.env.VITE_PUBLIC, 'favicon.ico'),
    webPreferences: {
      preload,
      nodeIntegration: true,
      contextIsolation: false,
    },
    // width: 1080,
    // height: 1920,
    // frame: false, // 去掉顶部编辑栏、
    // fullscreen: true, // 默认全屏
  });

  if (process.env.VITE_DEV_SERVER_URL) {
    win.loadURL(url);
    win.webContents.openDevTools();
  } else {
    win.loadFile(indexHtml);
  }

  win.webContents.on('did-finish-load', () => {
    win?.webContents.send('main-process-message', new Date().toLocaleString());
  });

  win.webContents.setWindowOpenHandler(({ url }) => {
    if (url.startsWith('https:')) shell.openExternal(url);
    return { action: 'deny' };
  });

  win.on('closed', () => {
    win = null;
  });
}

app.whenReady().then(createWindow);

app.on('second-instance', () => {
  if (win) {
    if (win.isMinimized()) win.restore();
    win.focus();
  }
});

app.on('activate', () => {
  const allWindows = BrowserWindow.getAllWindows();
  if (allWindows.length) {
    allWindows[0].focus();
  } else {
    createWindow();
  }
});

ipcMain.handle('open-win', (_, arg) => {
  let childWindow: BrowserWindow | null = new BrowserWindow({
    webPreferences: {
      preload,
      nodeIntegration: true,
      contextIsolation: false,
      webSecurity: false,
      devTools: true,
    },
  });

  if (process.env.VITE_DEV_SERVER_URL) {
    childWindow.loadURL(`${url}#${arg}`);
  } else {
    childWindow.loadFile(indexHtml, { hash: arg });
  }

  childWindow.on('closed', () => {
    childWindow = null;
  });
});

ipcMain.handle('get-printers', async (event: IpcMainInvokeEvent) => {
  const printers = await event.sender.getPrintersAsync();
  return printers;
});

ipcMain.on('print', (event, content) => {
  const printWindow = new BrowserWindow({ show: false });
  printWindow.loadURL(`data:text/html;charset=utf-8,${encodeURI(content)}`);
  printWindow.webContents.on('did-finish-load', () => {
    printWindow.webContents.print({
      silent: true,
      margins: {
        marginType: 'custom',
        top: 0,
        left: 0,
        right: 0,
        bottom: 0
      },
      printBackground: false,
      deviceName: '',
      copies: 1,
      collate: false,                // 不分页整理

    }, (success, failureReason) => {
      event.sender.send('print-response', { success, failureReason });
      printWindow.close();
      win.webContents.send('main-renderer')
    });
  });

  printWindow.on('closed', () => {
    printWindow.destroy();
  });
});

ipcMain.on('download-file', (event, url) => {
  // 打开保存对话框
  dialog.showSaveDialog({
      title: '保存文件',
      defaultPath: '下载文件.xlsx',
  }).then(result => {
      if (!result.canceled) {
          const file = fs.createWriteStream(result.filePath);

          http.get(url, response => {
              response.pipe(file);

              file.on('finish', () => {
                  file.close();
                  console.log('下载完成');
              });
          }).on('error', err => {
              fs.unlink(result.filePath);
              console.error('下载出错:', err.message);
          });
      }
  });
});


process.on('uncaughtException', (error) => {
  console.error('Unhandled Exception:', error);
});

process.on('unhandledRejection', (reason, promise) => {
  console.error('Unhandled Rejection at:', promise, 'reason:', reason);
});